/**
 * 
 */
package cn.hg.solon.youcan.job.provider;

import java.util.List;
import java.util.Map;

import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.cron.CronUtil;
import org.dromara.hutool.cron.pattern.CronPattern;
import org.dromara.hutool.cron.task.Task;
import org.dromara.hutool.db.PageResult;
import org.noear.solon.annotation.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.easy.query.api4j.client.EasyQuery;
import com.easy.query.api4j.select.Queryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.solon.annotation.Db;

import cn.hg.solon.youcan.common.constant.AppConstants;
import cn.hg.solon.youcan.common.constant.WebConstants;
import cn.hg.solon.youcan.common.enums.BeanStatus;
import cn.hg.solon.youcan.common.exception.ServiceException;
import cn.hg.solon.youcan.job.constant.JobStatus;
import cn.hg.solon.youcan.job.entity.EqJob;
import cn.hg.solon.youcan.job.entity.Job;
import cn.hg.solon.youcan.job.service.JobService;
import cn.hg.solon.youcan.job.utils.AbstractCronJob;
import cn.hg.solon.youcan.job.utils.CronDisallowConcurrentExecution;
import cn.hg.solon.youcan.job.utils.CronJobExecution;
import cn.hg.solon.youcan.job.utils.CronJobUtil;

/**
 * 定时任务服务实现
 * 
 * @author 胡高
 */
@Component
public class EqJobProvider implements JobService {
    protected Logger log = LoggerFactory.getLogger(this.getClass());

    @Db("db1")
    private EasyQuery easyQuery;

    private Queryable<EqJob> buildQuery(Map<String, Object> paraMap) {
        String group = (String)paraMap.get("group");
        String word = (String)paraMap.get("word");
        String sortField = (String)paraMap.get("sortField");
        String sortType = (String)paraMap.get("sortType");

        boolean customOrder = StrValidator.isNotBlank(sortField) && StrValidator.isNotBlank(sortType);

        // FROM sys_job AS t
        return this.easyQuery.queryable(EqJob.class)
            // WHERE t.`group` = ${group}
            .where(w -> w.eq(StrValidator.isNotBlank(group), EqJob::getGroup, group)
                // AND (t.`name` LIKE '%${word}%' OR t.`target` LIKE '%${word}%' OR t.`cron` LIKE '%${word}%')
                .and(StrValidator.isNotBlank(word),
                    a -> a.like(EqJob::getName, word)
                    .or().like(EqJob::getTarget, word)
                    .or().like(EqJob::getCron, word)))
            // ORDER BY ${sortField} DESC
            .orderBy(customOrder, ob -> ob.sqlNativeSegment(CharSequenceUtil.toUnderlineCase(sortField)),
                !CharSequenceUtil.equalsIgnoreCase(sortType, WebConstants.ORDER_DIRECTION_DESC));
    }


    private boolean checkCron(Job bean) {
        try{
            CronPattern.of(bean.getCron());
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

    @Override
    public boolean checkUnique(Job bean) {
        // FROM sys_job AS t
        return !this.easyQuery.queryable(EqJob.class)
            // WHERE t.`group` = ${bean.group} AND t.`name` = ${bean.name} AND t.`id` <> ${bean.id}
            .where(w -> w.eq(EqJob::getGroup, bean.getGroup())
                .eq(EqJob::getName, bean.getName())
                .ne(ObjUtil.isNotNull(bean.getId()), EqJob::getId, bean.getId())).any();
    }

    @Override
    public boolean clear() {
        return this.easyQuery.deletable(EqJob.class).allowDeleteStatement(true).executeRows() > 0;
    }

    private AbstractCronJob createTask(Job job) {
        /*
         * 克隆Job
         */
        Job tempJob = BeanUtil.copyProperties(job, Job.class);

        if (tempJob.getConcurrent()) {
            return new CronJobExecution(tempJob);
        }

        return new CronDisallowConcurrentExecution(tempJob);
    }

    @Override
    public boolean delete(List<Integer> idList) {
        return this.easyQuery.deletable(EqJob.class).whereByIds(idList).executeRows() > 0;
    }

    @Override
    public Job get(Integer id) {
        return this.easyQuery.queryable(EqJob.class).whereById(id).firstOrNull();
    }

    @Override
    public void init() throws ServiceException {
        /*
         * 如果Cron服务没有启动，则启动之
         */
        List<EqJob> jobList = this.easyQuery.queryable(EqJob.class).toList();
        for (Job job : jobList) {
            if (CharSequenceUtil.equals(job.getStatus(), JobStatus.OFF.name())) {
                this.pause(job);
            } else if (CharSequenceUtil.equals(job.getStatus(), JobStatus.ON.name())) {
                this.resume(job);
            }
        }
    }

    @Override
    public boolean insert(Job bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "任务名称已经存在，请更换其它值！");
        }

        if (!this.checkCron(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "Cron表达式校验不通过，请更换其它值！");
        }

        EqJob cloneBean = BeanUtil.copyProperties(bean, EqJob.class);

        return this.easyQuery.insertable(cloneBean).executeRows() > 0;
    }

    @Override
    public PageResult<? extends Job> pageBy(int pageNumber, int pageSize, Map<String, Object> paraMap) {
        EasyPageResult<EqJob> pageList = this.buildQuery(paraMap).toPageResult(Convert.toLong(pageNumber), pageSize);

        PageResult<EqJob> result = new PageResult<>();
        result.addAll(pageList.getData());
        result.setTotal(Convert.toInt(pageList.getTotal()));

        return result;
    }

    @Override
    public boolean pause(Job bean) {
        /*
         * 生成任务Key
         */
        String key = CronJobUtil.genTaskKey(bean);

        /*
         * 无任务
         */
        if (ObjUtil.isNull(CronUtil.getScheduler().getTask(key))) {
            return true;
        }

        /*
         * 有任务，则移除之
         */
        CronUtil.getScheduler().deschedule(key);

        EqJob exist = (EqJob)this.get(bean.getId());
        if (!CharSequenceUtil.equals(exist.getStatus(), JobStatus.OFF.name())) {
            exist.setStatus(JobStatus.OFF.name());
            this.update(exist);
        }

        this.log.debug("任务 [{}] 停用成功。。。", exist.getName());

        return true;
    }

    @Override
    public boolean resume(Job bean) {
        /*
         * 生成任务Key
         */
        String key = CronJobUtil.genTaskKey(bean);

        this.startCron();

        /*
         * 无任务，则创建之
         */
        if (ObjUtil.isNull(CronUtil.getScheduler().getTask(key))) {
            /*
             * 创建Task
             */
            Task task = this.createTask(bean);

            CronUtil.getScheduler().schedule(key, bean.getCron(), task);

            EqJob exist = (EqJob)this.get(bean.getId());
            if (!CharSequenceUtil.equals(exist.getStatus(), BeanStatus.ON.name())) {
                exist.setStatus(BeanStatus.ON.name());
                this.update(exist);
            }
            this.log.debug("任务 [{}] 启用成功。。。", bean.getName());
        } else {
            /*
             * 有任务，则更新之
             */
            CronUtil.getScheduler().updatePattern(key, CronPattern.of(bean.getCron()));

            this.log.debug("任务 [{}] 更新成功。。。", bean.getName());
        }

        return true;
    }

    private void startCron() {
        if (!CronUtil.getScheduler().isStarted()) {
            CronUtil.start();
        }
    }

    @Override
    public boolean test(Job bean) {
        /*
         * 创建Task
         */
        Task task = this.createTask(bean);

        /*
         * 执行任务（单次）
         */
        try {
            task.execute();
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

    @Override
    public boolean update(Job bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "任务名称已经存在，请更换其它值！");
        }

        if (!this.checkCron(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "Cron表达式校验不通过，请更换其它值！");
        }

        EqJob cloneBean = (EqJob)this.get(bean.getId());

        BeanUtil.copyProperties(bean, cloneBean, CopyOptions.of().setIgnoreNullValue(true));

        return this.easyQuery.updatable(cloneBean).executeRows() > 0;
    }

}
